package com.youi.web;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.sec.sdk.exception.SecGatewayException;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Groupleaderbank;
import com.youi.entity.Leaderprofit;
import com.youi.entity.Leaderprofitdetail;
import com.youi.entity.Leaderwithdraw;
import com.youi.entity.Merchantwithdraw;
import com.youi.entity.Merchantwithdrawdetail;
import com.youi.entity.Plamtwithdraw;
import com.youi.entity.Plamtwithdrawdetail;
import com.youi.entity.Platmerchantno;
import com.youi.entity.Sharecloudrecord;
import com.youi.entity.Sysuser;
import com.youi.entity.Tremittance;
import com.youi.entity.Userorder;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.GroupleaderbankService;
import com.youi.service.LeaderprofitService;
import com.youi.service.LeaderprofitdetailService;
import com.youi.service.LeaderwithdrawService;
import com.youi.service.MerchantService;
import com.youi.service.MerchantwithdrawService;
import com.youi.service.MerchantwithdrawdetailService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.PlamtwithdrawService;
import com.youi.service.PlamtwithdrawdetailService;
import com.youi.service.PlatmerchantnoService;
import com.youi.service.SharecloudrecordService;
import com.youi.service.TremittanceService;
import com.youi.service.UserorderService;
import com.youi.service.YibaodivideService;
import com.youi.service.YibaopaymentService;
import com.youi.service.impl.AsyncTremittanceService;
import com.youi.third.shareclound.SharecloundUtil;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.EasyPoiUtil;
import com.youi.util.ExcelStyleUtil;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 打款申请信息控制层
 *
 * @author Administrator
 */
@Controller
public class TremittanceController extends HttpRequestManage {

    @Autowired
    private TremittanceService tremittanceService;
    @Autowired
    private MerchantwithdrawService merchantwithdrawService;
    @Autowired
    private MerchantwithdrawdetailService merchantwithdrawdetailService;
    @Autowired
    private UserorderService userorderService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private YibaodivideService yibaodivideService;
    @Autowired
    private OrderprofitdetailService orderprofitdetailService;
    @Autowired
    private PlamtwithdrawService plamtwithdrawService;
    @Autowired
    private PlamtwithdrawdetailService plamtwithdrawdetailService;
    @Autowired
    private LeaderwithdrawService leaderwithdrawService;
    @Autowired
    private GroupleaderbankService groupleaderbankService;
    @Autowired
    private SharecloudrecordService sharecloudrecordService;
    @Autowired
    private PlatmerchantnoService platmerchantnoService;
    @Autowired
    private LeaderprofitService leaderprofitService;
    @Autowired
    private LeaderprofitdetailService leaderprofitdetailService;

    @Autowired
    private AsyncTremittanceService asyncTremittanceService;


    /**
     * I-99
     * 查询打款申请信息列表
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getTremittance")
    public String getTremittance(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        Integer type = optInteger(Common.TYPE, request);
        Integer status = optInteger(Common.STATUS, request);
        String withdrawNo = optString("withdrawNo", request);
        String des = optString("des", request, Common.DESC);
        String pms = optString("pms", request);
        Date start = optDate("start", request, "yyyy-MM-dd HH:mm:ss");
        Date end = optDate("end", request, "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        //打款类型
        if (type != null) {
            prams.put(Common.TYPE, type);
        }
        //审核状态
        if (status != null) {
            prams.put(Common.STATUS, status);
        }
        //提现单号
        if (withdrawNo != null && withdrawNo.trim().length() > 0) {
            prams.put("withdrawNo", withdrawNo);
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        Map<String, Object> searchPram = null;
        if (pms != null) {
            searchPram = new HashMap<String, Object>();
        }
        Map<String, Object> startTime = null;
        if (start != null) {
            startTime = new HashMap<String, Object>();
            startTime.put(Common.GMTCREATED, start);
        }
        Map<String, Object> endTime = null;
        if (end != null) {
            endTime = new HashMap<String, Object>();
            endTime.put(Common.GMTCREATED, end);
        }
        List<Tremittance> tremittanceList = tremittanceService.getByParamsList(prams, searchPram, sortPram, (pageIndex - 1) * pageNum, pageNum, startTime, endTime);
        if (tremittanceList == null || tremittanceList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = tremittanceService.getCountByParamss(prams, searchPram, startTime, endTime);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, tremittanceList);        //jsonObjectList json对象集合
        tremittanceService.getTremittanceMsg(tremittanceList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * I-100
     * 导出打款申请excel
     */
    @Deprecated
    @ResponseBody
    @RequestMapping("toExcelTremittance")
    public String toExcelTremittance(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Integer type = optInteger(Common.TYPE, request);
        Integer status = optInteger(Common.STATUS, request);
        String withdrawNo = optString("withdrawNo", request);
        String des = optString("des", request, Common.DESC);
        String pms = optString("pms", request);
        Date start = optDate("start", request, "yyyy-MM-dd HH:mm:ss");
        Date end = optDate("end", request, "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        //打款类型
        if (type != null) {
            prams.put(Common.TYPE, type);
        }
        //审核状态
        if (status != null) {
            prams.put(Common.STATUS, status);
        }
        //提现单号
        if (withdrawNo != null && withdrawNo.trim().length() > 0) {
            prams.put("withdrawNo", withdrawNo);
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        Map<String, Object> searchPram = null;
        if (pms != null) {
            searchPram = new HashMap<String, Object>();
        }
        Map<String, Object> startTime = null;
        if (start != null) {
            startTime = new HashMap<String, Object>();
            startTime.put(Common.GMTCREATED, start);
        }
        Map<String, Object> endTime = null;
        if (end != null) {
            endTime = new HashMap<String, Object>();
            endTime.put(Common.GMTCREATED, end);
        }
        List<Tremittance> tremittanceList = tremittanceService.getByParamsAll(prams, searchPram, sortPram, startTime, endTime);
        if (tremittanceList == null || tremittanceList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        tremittanceService.getTremittanceMsg(tremittanceList);
        tremittanceService.toExcelTremittance(request, tremittanceList);
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * 导出打款申请
     *
     * @param param
     * @param request
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "sysUserGetInfo/exportRemittanceApply", produces = "application/json")
    public void exportRemittanceApply(@RequestBody Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //根据条件查询全部数据,不分页
        List<Map<String, Object>> exportList = tremittanceService.listRemittanceApplyByParam(param);
        if (CollectionUtils.isEmpty(exportList)) {
            throw new BusinessException(-1, "没有要导出的数据");
        }

        try {
            String fileName = "打款申请" + DateUtil.simpyMdHHmmss.format(new Date());
            ExportParams exportParams = new ExportParams(null, "打款申请", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);

            List<ExcelExportEntity> excelExportEntityList = Lists.newArrayList();
            excelExportEntityList.add(new ExcelExportEntity("提现单号", "withdrawNo", 20));
            excelExportEntityList.add(new ExcelExportEntity("打款类型", "typeTxt", 15));
            excelExportEntityList.add(new ExcelExportEntity("分润比例", "profitRatio", 15));
            excelExportEntityList.add(new ExcelExportEntity("手续费", "serviceCharge", 10));
            excelExportEntityList.add(new ExcelExportEntity("订单总金额", "orderAmount", 15));
            excelExportEntityList.add(new ExcelExportEntity("实际打款金额", "realityAmount", 15));
            excelExportEntityList.add(new ExcelExportEntity("团长打款金额", "leaderAmount", 15));
            excelExportEntityList.add(new ExcelExportEntity("提现创建人", "createdUserName", 15));
            excelExportEntityList.add(new ExcelExportEntity("收款方", "payeeName", 25));
            excelExportEntityList.add(new ExcelExportEntity("打款方式", "payTypeTxt", 10));
            excelExportEntityList.add(new ExcelExportEntity("审核状态", "statusTxt", 10));
            excelExportEntityList.add(new ExcelExportEntity("审核人", "agreeUsername", 15));
            excelExportEntityList.add(new ExcelExportEntity("审核时间", "gmtAgree", 20));
            excelExportEntityList.add(new ExcelExportEntity("打款时间", "gmtReality", 20));
            excelExportEntityList.add(new ExcelExportEntity("创建时间", "gmtCreated", 20));

            EasyPoiUtil.exportExcel(fileName, exportParams, excelExportEntityList, exportList, request, response);
        } catch (Exception ex) {
            throw new BusinessException(-1, "导出数据失败");
        }
    }

    /**
     * I-105
     * 审核打款申请
     *
     * @throws IOException
     * @throws SecGatewayException
     * @throws InterruptedException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/applyTremittanceById")
    public String getTremittanceById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException, SecGatewayException, InterruptedException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        String ids = getString("ids", request);
        Integer status = getInteger(Common.STATUS, request);
        List<Long> idsList = ObjectUtil.getIdListByIds(ids);
        if (idsList == null || idsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.ID, idsList);
        List<Tremittance> tremittanceList = tremittanceService.getByParams(params);
        if (tremittanceList == null || tremittanceList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        for (Tremittance tremittance : tremittanceList) {
            if (tremittance.getStatus() != 0 && tremittance.getStatus() != 2) {
                return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "打款申请非可审核状态无法操作");
            }
            Integer result = null;
            if (tremittance.getType() == 0) {
                if (status == 1) {
                    tremittance.setPayStatus(1);
                    tremittance.setStatus(1); //1同意打款
                    //预先保存GmtAgree和AgreeUserId
                    tremittance.setGmtAgree(new Date());
                    tremittance.setAgreeUserId(sysuser.getId());
                    tremittanceService.saveOrUpdate(tremittance);
                    result = divideMerchantByAgree(tremittance, sysuser);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                } else if (status == -1) {
                    result = divideMerchantByRefuse(tremittance);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                    tremittance.setStatus(-1);
                    tremittanceService.saveOrUpdate(tremittance);
                } else if (status == 2) {
                    tremittance.setGmtAgree(new Date());
                    tremittance.setStatus(2);
                    tremittance.setAgreeUserId(sysuser.getId());
                    tremittanceService.saveOrUpdate(tremittance);
                }
            } else if (tremittance.getType() == 1) {
                if (status == 1) {
                    tremittance.setPayStatus(1);
                    tremittance.setStatus(1); //1同意打款
                    //预先保存GmtAgree和AgreeUserId
                    tremittance.setGmtAgree(new Date());
                    tremittance.setAgreeUserId(sysuser.getId());
                    tremittanceService.saveOrUpdate(tremittance);
                    result = dividePlatformByAgree(tremittance, sysuser);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                } else if (status == -1) {
                    result = dividePlatformByRefuse(tremittance);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                } else if (status == 2) {
                    tremittance.setGmtAgree(new Date());
                    tremittance.setStatus(2);
                    tremittance.setAgreeUserId(sysuser.getId());
                    tremittanceService.saveOrUpdate(tremittance);
                }
            } else if (tremittance.getType() == 2) {
                if (status == 1) {
                    result = divideLeaderByAgree(tremittance, sysuser);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                } else if (status == -1) {
                    result = divideLeaderByRefuse(tremittance);
                    if (result == 0) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "操作失败");
                    }
                } else if (status == 2) {
                    tremittance.setGmtAgree(new Date());
                    tremittance.setStatus(2);
                    tremittance.setAgreeUserId(sysuser.getId());
                    tremittanceService.saveOrUpdate(tremittance);
                }
            }
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * 查询所有打款申请信息
     *
     * @param modelMap
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("getAllTremittance")
    public String getAllTremittance(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        List<Tremittance> tremittanceList = tremittanceService.getByParams(null);
        if (tremittanceList == null || tremittanceList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", tremittanceList);//jsonObjectList	json对象集合
    }

    @ResponseBody
    @RequestMapping("testFinishMerchantDivide")
    public String testFinishMerchantDivide(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        try {
            asyncTremittanceService.finishMerchantDivide(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }


    @ResponseBody
    @RequestMapping("testTrancationOnly")
    public String testTrancationOnly(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        asyncTremittanceService.testTrancationOnly(id);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "任务已启动");
    }


//		/**
//		 * 同意供应商打款处理打款处理
//		 * @param tremittance
//		 * @throws IOException
//		 * @throws InterruptedException
//		 */
//		private Integer divideMerchantByAgree(Tremittance tremittance,Sysuser sysuser) throws IOException, InterruptedException {
//			Map<String, Object> prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put("twithdrawNo", tremittance.getWithdrawNo());
//			Merchantwithdraw merchantwithdraw=merchantwithdrawService.getByParam(prams);
//			if (merchantwithdraw==null) {
//				return 0;
//			}
//			prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put("withdrawNo", merchantwithdraw.getTwithdrawNo());
//			List<Merchantwithdrawdetail> merchantwithdrawdetailList=merchantwithdrawdetailService.getByParams(prams);
//			if (merchantwithdrawdetailList==null||merchantwithdrawdetailList.size()==0) {
//				return 0;
//			}
//			Double realityAmount=0.0;
//			for (Merchantwithdrawdetail merchantwithdrawdetail : merchantwithdrawdetailList) {
//				LogUtil.Info("===========本次分账的任务数量:"+merchantwithdrawdetailList.size());
//				Thread.currentThread().sleep(1000);
//				if (merchantwithdrawdetail.getProfitStatus()==0) {
//					prams=new HashMap<String, Object>();
//					prams.put(Common.DELSTATUS, DelStatus.NODEL);
//					prams.put("orderNo", merchantwithdrawdetail.getOrderNo());
//					Userorder userorder=userorderService.getByParam(prams);
//					if (userorder==null) {
//						merchantwithdrawdetail.setMerchantStatus(4);
//						merchantwithdrawdetail.setProfitStatus(-1);
//						merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//						continue;
//					}
//					prams=new HashMap<String, Object>();
//					prams.put(Common.DELSTATUS, DelStatus.NODEL);
//					Map<String, Object> searchParams=new HashMap<String, Object>();
//					searchParams.put("orderNos", userorder.getOrderNo());
//					Yibaopayment yibaopayment=yibaopaymentService.getByParam(prams,searchParams,null);
//					if (yibaopayment==null) {
//						merchantwithdrawdetail.setMerchantStatus(4);
//						merchantwithdrawdetail.setProfitStatus(-1);
//						userorder.setMerchantStatus(4);
//						merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//						continue;
//					}
//					Merchant merchant=merchantService.get(userorder.getMerchantId());
//					if (merchant==null) {
//						merchantwithdrawdetail.setMerchantStatus(4);
//						merchantwithdrawdetail.setProfitStatus(-1);
//						userorder.setMerchantStatus(4);
//						merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//						continue;
//					}
//					prams=new HashMap<String, Object>();
//					prams.put(Common.DELSTATUS, DelStatus.NODEL);
//					prams.put("orderNo", userorder.getOrderNo());
//					Orderprofitdetail orderprofitdetail=orderprofitdetailService.getByParam(prams);
//					if (orderprofitdetail==null) {
//						merchantwithdrawdetail.setMerchantStatus(4);
//						merchantwithdrawdetail.setProfitStatus(-1);
//						userorder.setMerchantStatus(4);
//						merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//						continue;
//					}
//					prams=new HashMap<String, Object>();
//					prams.put(Common.DELSTATUS, DelStatus.NODEL);
//					prams.put("orderNo", userorder.getOrderNo());
//					Yibaodivide yibaodivide=yibaodivideService.getByParam(prams);
//					if (yibaodivide==null) {
//						Divideresult divideresult=YibaopayUtil.yibaoDivideToMerchant(yibaopayment.getSerialNumber(),
//						yibaopayment.getPaymentNo(), orderprofitdetail.getMerAmount(), merchant.getMerchantNo());
//						if (divideresult!=null&&divideresult.getCode().equals("OPR00000")) {
//							yibaodivide=new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), userorder.getOrderNo(), divideresult.getUniqueOrderNo(),
//							divideresult.getDivideRequestId(), divideresult.getDivideDetail());
//							yibaodivideService.saveOrUpdate(yibaodivide);
//							merchantwithdrawdetail.setMerchantStatus(3);
//							merchantwithdrawdetail.setProfitStatus(1);
//							merchantwithdrawdetail.setGmtComplete(new Date());
//							merchantwithdrawdetail.setGmtWithdraw(new Date());
//							userorder.setMerchantStatus(3);
//							userorder.setGmtMerchantWith(new Date());
//							merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//							userorderService.saveOrUpdate(userorder);
//							merchantwithdraw.setStatus(3);
//							merchantwithdrawService.saveOrUpdate(merchantwithdraw);
//							realityAmount+=orderprofitdetail.getMerAmount();
//							tremittance.setPayStatus(2);
//						}else {
//							merchantwithdrawdetail.setMerchantStatus(4);
//							merchantwithdrawdetail.setProfitStatus(-1);
//							userorder.setMerchantStatus(4);
//							merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//							userorderService.saveOrUpdate(userorder);
//							tremittance.setPayStatus(-1);
//						}
//					}else {
//						JSONObject jsonObject=YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
//						if (jsonObject!=null&&!jsonObject.getString("code").equals("OPR00000")) {
//							merchantwithdrawdetail.setMerchantStatus(4);
//							merchantwithdrawdetail.setProfitStatus(-1);
//							userorder.setMerchantStatus(4);
//							merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//							userorderService.saveOrUpdate(userorder);
//							tremittance.setPayStatus(-1);
//						}else {
//							merchantwithdrawdetail.setMerchantStatus(3);
//							merchantwithdrawdetail.setProfitStatus(1);
//							merchantwithdrawdetail.setGmtComplete(new Date());
//							merchantwithdrawdetail.setGmtWithdraw(new Date());
//							userorder.setMerchantStatus(3);
//							userorder.setGmtMerchantWith(new Date());
//							merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
//							userorderService.saveOrUpdate(userorder);
//							merchantwithdraw.setStatus(3);
//							merchantwithdrawService.saveOrUpdate(merchantwithdraw);
//							realityAmount+=orderprofitdetail.getMerAmount();
//							tremittance.setPayStatus(2);
//						}
//					}
//				}
//			}
//			tremittance.setStatus(1);
//			tremittance.setGmtAgree(new Date());
//			tremittance.setGmtReality(new Date());
//			tremittance.setAgreeUserId(sysuser.getId());
//			tremittance.setRealityAmount(ObjectUtil.sciCal(realityAmount, 2));
//			tremittanceService.saveOrUpdate(tremittance);
//			return 1;
//		}

    /**
     * 同意供应商打款处理打款处理
     * 该方法从原本的实时处理，改为对于每条明细，调用异步处理（进入线程池队列）
     * 当异步处理全部完成的时候，自然会更新主表状态
     */
    private Integer divideMerchantByAgree(Tremittance tremittance, Sysuser sysuser) throws IOException, InterruptedException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("twithdrawNo", tremittance.getWithdrawNo());
        Merchantwithdraw merchantwithdraw = merchantwithdrawService.getByParam(prams);
        if (merchantwithdraw == null) {
            return 0;
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("withdrawNo", merchantwithdraw.getTwithdrawNo());
        List<Merchantwithdrawdetail> merchantwithdrawdetailList = merchantwithdrawdetailService.getByParams(prams);
        if (merchantwithdrawdetailList == null || merchantwithdrawdetailList.size() == 0) {
            return 0;
        }
        for (Merchantwithdrawdetail merchantwithdrawdetail : merchantwithdrawdetailList) {
            //调用异步处理
            asyncTremittanceService.divideMerchantByAgree(merchantwithdrawdetail.getId());
        }
        return 1;
    }

    /**
     * 拒绝供应商打款处理打款处理
     *
     * @param tremittance
     * @throws IOException
     */
    private Integer divideMerchantByRefuse(Tremittance tremittance) throws IOException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("twithdrawNo", tremittance.getWithdrawNo());
        Merchantwithdraw merchantwithdraw = merchantwithdrawService.getByParam(prams);
        if (merchantwithdraw != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("withdrawNo", merchantwithdraw.getTwithdrawNo());
            List<Merchantwithdrawdetail> merchantwithdrawdetailList = merchantwithdrawdetailService.getByParams(prams);
            if (merchantwithdrawdetailList != null && merchantwithdrawdetailList.size() > 0) {
                for (Merchantwithdrawdetail merchantwithdrawdetail : merchantwithdrawdetailList) {
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    prams.put("orderNo", merchantwithdrawdetail.getOrderNo());
                    Userorder userorder = userorderService.getByParam(prams);
                    if (userorder != null) {
                        merchantwithdrawdetail.setMerchantStatus(4);
                        userorder.setMerchantStatus(4);
                        merchantwithdrawdetailService.saveOrUpdate(merchantwithdrawdetail);
                        userorderService.saveOrUpdate(userorder);
                    }
                }
            }
            merchantwithdraw.setStatus(-1);
            merchantwithdrawService.saveOrUpdate(merchantwithdraw);
            return 1;
        }
        return 0;
    }


//		private Integer dividePlatformByAgree(Tremittance tremittance,Sysuser sysuser) throws IOException {
//			Platmerchantno platmerchantno=platmerchantnoService.get(1L);
//			if (platmerchantno==null) {
//				return 0;
//			}
//			Map<String, Object> prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put("withdrawNo", tremittance.getWithdrawNo());
//			Plamtwithdraw plamtwithdraw=plamtwithdrawService.getByParam(prams);
//			plamtwithdrawService.getPlamtwithdraw(plamtwithdraw);
//			if (plamtwithdraw==null) {
//				return 0;
//			}
//			List<Plamtwithdrawdetail> plamtwithdrawdetailList=plamtwithdraw.getPlamtwithdrawdetailList();
//			if (plamtwithdrawdetailList==null||plamtwithdrawdetailList.size()==0) {
//				return 0;
//			}
//			for (Plamtwithdrawdetail plamtwithdrawdetail : plamtwithdrawdetailList) {
//				prams=new HashMap<String, Object>();
//				prams.put(Common.DELSTATUS, DelStatus.NODEL);
//				prams.put("orderNo", plamtwithdrawdetail.getOrderNo());
//				Userorder userorder=userorderService.getByParam(prams);
//				if (userorder==null) {					
//					tremittance.setGmtAgree(new Date());
//					tremittance.setPayStatus(-1);
//					tremittanceService.saveOrUpdate(tremittance);
//					plamtwithdrawdetail.setStatus(4);
//					plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);					
//					continue;
//				}
//				prams=new HashMap<String, Object>();
//				prams.put(Common.DELSTATUS, DelStatus.NODEL);
//				Map<String, Object> searchParams=new HashMap<String, Object>();
//				searchParams.put("orderNos", userorder.getOrderNo());
//				Yibaopayment yibaopayment=yibaopaymentService.getByParam(prams,searchParams,null);
//				if (yibaopayment==null) {
//					userorder.setPlatformStatus(4);
//					userorderService.saveOrUpdate(userorder);
//					plamtwithdrawdetail.setStatus(4);
//					plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);					
//					tremittance.setGmtAgree(new Date());
//					tremittance.setPayStatus(-1);					
//					tremittanceService.saveOrUpdate(tremittance);
//					continue;
//				}
//				prams=new HashMap<String, Object>();
//				prams.put(Common.DELSTATUS, DelStatus.NODEL);
//				prams.put("orderNo", userorder.getOrderNo());
//				Orderprofitdetail orderprofitdetail=orderprofitdetailService.getByParam(prams);
//				if (orderprofitdetail==null) {
//					userorder.setPlatformStatus(4);
//					userorderService.saveOrUpdate(userorder);
//					plamtwithdrawdetail.setStatus(4);
//					plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);					
//					tremittance.setGmtAgree(new Date());
//					tremittance.setPayStatus(-1);					
//					tremittanceService.saveOrUpdate(tremittance);
//					continue;
//				}
//				Divideresult divideresult =YibaopayUtil.yibaoDivideToMerchant(yibaopayment.getSerialNumber(), 
//				yibaopayment.getPaymentNo(), orderprofitdetail.getPlatAmount(), platmerchantno.getMerchantNo());															
//				Yibaodivide yibaodivide=null;
//				if (divideresult!=null&&divideresult.getCode().equals("OPR00000")) {
//					yibaodivide=new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), userorder.getOrderNo(), divideresult.getUniqueOrderNo(), 
//					divideresult.getDivideRequestId(), divideresult.getDivideDetail());
//					plamtwithdrawdetail.setStatus(3);
//					userorder.setPlatformStatus(3);
//					userorder.setGmtPlatformWith(new Date());
//					plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);
//					userorderService.saveOrUpdate(userorder);
//					plamtwithdraw.setStatus(3);
//					plamtwithdrawService.saveOrUpdate(plamtwithdraw);
//					tremittance.setGmtAgree(new Date());
//					tremittance.setGmtReality(yibaodivide.getGmtCreated());
//					tremittance.setStatus(1);
//					tremittance.setPayStatus(2);
//					tremittance.setAgreeUserId(sysuser.getId());
//					tremittance.setRealityAmount(orderprofitdetail.getPlatAmount());
//					tremittance.setServiceCharge(plamtwithdraw.getServiceCharge());
//					tremittanceService.saveOrUpdate(tremittance);										
//				}else {
//					yibaodivide=new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), userorder.getOrderNo(), divideresult.getUniqueOrderNo(), 
//					divideresult.getDivideRequestId(), divideresult.getDivideDetail());
//					yibaodivideService.saveOrUpdate(yibaodivide);
//					plamtwithdrawdetail.setStatus(4);
//					userorder.setPlatformStatus(4);
//					tremittance.setGmtAgree(new Date());
//					tremittance.setPayStatus(-1);
//					plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);
//					tremittanceService.saveOrUpdate(tremittance);
//					userorderService.saveOrUpdate(userorder);
//				}
//			}
//			return 1;
//		}

    /**
     * 同意平台提现打款处理
     *
     * @param tremittance
     * @throws IOException
     */
    private Integer dividePlatformByAgree(Tremittance tremittance, Sysuser sysuser) throws IOException {
        Platmerchantno platmerchantno = platmerchantnoService.get(1L);
        if (platmerchantno == null) {
            return 0;
        }
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("withdrawNo", tremittance.getWithdrawNo());
        Plamtwithdraw plamtwithdraw = plamtwithdrawService.getByParam(prams);
        plamtwithdrawService.getPlamtwithdraw(plamtwithdraw);
        if (plamtwithdraw == null) {
            return 0;
        }
        List<Plamtwithdrawdetail> plamtwithdrawdetailList = plamtwithdraw.getPlamtwithdrawdetailList();
        if (plamtwithdrawdetailList == null || plamtwithdrawdetailList.size() == 0) {
            return 0;
        }
        for (Plamtwithdrawdetail plamtwithdrawdetail : plamtwithdrawdetailList) {
            //调用异步分账
            //todo 用异步方式调用的时候，当一笔订单分多次调用的时候会报OPR13021错误
            asyncTremittanceService.dividePlatformByAgree(plamtwithdrawdetail.getId(), platmerchantno);
        }
        return 1;
    }

    /**
     * 拒绝平台打款处理
     *
     * @param tremittance
     * @throws IOException
     */
    private Integer dividePlatformByRefuse(Tremittance tremittance) throws IOException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("withdrawNo", tremittance.getWithdrawNo());
        Plamtwithdraw plamtwithdraw = plamtwithdrawService.getByParam(prams);
        plamtwithdrawService.getPlamtwithdraw(plamtwithdraw);
        if (plamtwithdraw != null) {
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("withdrawNo", plamtwithdraw.getWithdrawNo());
            List<Plamtwithdrawdetail> plamtwithdrawdetailList = plamtwithdraw.getPlamtwithdrawdetailList();
            if (plamtwithdrawdetailList != null && plamtwithdrawdetailList.size() > 0) {
                for (Plamtwithdrawdetail plamtwithdrawdetail : plamtwithdrawdetailList) {
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    prams.put("orderNo", plamtwithdrawdetail.getOrderNo());
                    Userorder userorder = userorderService.getByParam(prams);
                    if (userorder != null) {
                        plamtwithdrawdetail.setStatus(4);
                        userorder.setMerchantStatus(4);
                        plamtwithdrawdetailService.saveOrUpdate(plamtwithdrawdetail);
                        userorderService.saveOrUpdate(userorder);
                    }
                }
                plamtwithdraw.setStatus(-1);
                plamtwithdrawService.saveOrUpdate(plamtwithdraw);
                return 1;
            }
        }
        return 0;
    }

    /**
     * 同意团长打款申请
     *
     * @param tremittance
     * @return
     * @throws IOException
     * @throws SecGatewayException
     */
    private Integer divideLeaderByAgree(Tremittance tremittance, Sysuser sysuser) throws IOException, SecGatewayException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", tremittance.getWithdrawNo());
        Leaderwithdraw leaderwithdraw = leaderwithdrawService.getByParam(prams);
        if (leaderwithdraw == null) {
            return 0;
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("leaderId", leaderwithdraw.getLeaderId());
        Groupleaderbank groupleaderbank = groupleaderbankService.getByParam(prams);
        if (groupleaderbank == null) {
            return 0;
        }
        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
        if (leaderprofit == null) {
            return 0;
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", tremittance.getWithdrawNo());
        Sharecloudrecord sharecloudrecord = sharecloudrecordService.getByParam(prams);
        if (sharecloudrecord == null) {
            sharecloudrecord = new Sharecloudrecord(tremittance.getWithdrawNo(), tremittance.getId());
            sharecloudrecordService.saveOrUpdate(sharecloudrecord);
        }
        String payresult = SharecloundUtil.shareCloundPay(sharecloudrecord.getCustBatchNo(), tremittance.getLeaderAmount().toString(),
                tremittance.getWithdrawNo(), groupleaderbank.getRealName(), groupleaderbank.getBank(), groupleaderbank.getBankCardNo(), groupleaderbank.getIdCard());
        JSONObject data = JSONObject.parseObject(payresult);
        if (data == null) {
            return 0;
        }
        sharecloudrecord.setCode(data.getString("code"));
        sharecloudrecord.setMessage(data.getString("message"));
        if (data.getString("code").equals("0000")) {
            sharecloudrecord.setPlatBatchNo(data.getString("platBatchNo"));
            sharecloudrecord.setRecvType(data.getString("recvType"));
            sharecloudrecord.setBatchAmt(data.getDouble("batchAmt"));
            sharecloudrecord.setBatchServFeeAmt(data.getDouble("batchServFeeAmt"));
            sharecloudrecord.setTotalDeduction(data.getDouble("totalDeduction"));
            sharecloudrecord.setBatchStatus(data.getInteger("batchStatus"));
            sharecloudrecordService.saveOrUpdate(sharecloudrecord);
            tremittance.setStatus(1);
            tremittance.setCloudServiceCharge(sharecloudrecord.getBatchServFeeAmt());
            tremittance.setRealityExpend(sharecloudrecord.getTotalDeduction());
            tremittance.setPayStatus(1);
            tremittance.setGmtAgree(new Date());
            tremittance.setAgreeUserId(sysuser.getId());
            tremittance.setRealityAmount(leaderwithdraw.getRealAnt());
            tremittance.setServiceCharge(leaderwithdraw.getCommission());
        } else {
            tremittance.setStatus(1);
            tremittance.setPayStatus(-1);
            tremittance.setGmtAgree(new Date());
            tremittance.setAgreeUserId(sysuser.getId());
            leaderprofit.setBalance(ObjectUtil.sciCal(leaderprofit.getBalance() + leaderwithdraw.getAmount(), 2));
            leaderprofit.setWithdres(ObjectUtil.sciCal(leaderprofit.getWithdres() - leaderwithdraw.getAmount(), 2));
            leaderprofitService.saveOrUpdate(leaderprofit);
            leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderprofit.getLeaderId(), 0, leaderwithdraw.getAmount(), "提现失败退回", tremittance.getWithdrawNo()));
        }
        sharecloudrecordService.saveOrUpdate(sharecloudrecord);
        tremittanceService.saveOrUpdate(tremittance);
        return 1;
    }

    /**
     * 拒绝团长打款处理
     *
     * @param tremittance
     * @throws IOException
     */
    private Integer divideLeaderByRefuse(Tremittance tremittance) throws IOException {
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", tremittance.getWithdrawNo());
        Leaderwithdraw leaderwithdraw = leaderwithdrawService.getByParam(prams);
        if (leaderwithdraw == null) {
            return 0;
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("leaderId", leaderwithdraw.getLeaderId());
        Leaderprofit leaderprofit = leaderprofitService.getByParam(prams);
        if (leaderprofit == null) {
            return 0;
        }
        leaderwithdraw.setStatus(-1);
        leaderwithdrawService.saveOrUpdate(leaderwithdraw);
        tremittance.setStatus(-1);
        tremittanceService.saveOrUpdate(tremittance);
        leaderprofit.setBalance(ObjectUtil.sciCal(leaderprofit.getBalance() + leaderwithdraw.getAmount(), 2));
        leaderprofit.setWithdres(ObjectUtil.sciCal(leaderprofit.getWithdres() - leaderwithdraw.getAmount(), 2));
        leaderprofitService.saveOrUpdate(leaderprofit);
        leaderprofitdetailService.saveOrUpdate(new Leaderprofitdetail(leaderprofit.getLeaderId(), 0, leaderwithdraw.getAmount(), "提现失败退回", tremittance.getWithdrawNo()));
        return 1;
    }


}
